package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Size;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        User user = userMapper.getByUserId(BaseContext.getCurrentId());
        AddressBook addressBook = AddressBook.builder().isDefault(1).build();
        Orders orders =new Orders();
        Long userId= BaseContext.getCurrentId();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        String number = UUID.randomUUID().toString().replace("_", "7");
        orders.setNumber(number);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        addressBook = addressBookMapper.list(addressBook).get(0);
        orders.setUserName(user.getName());
        orders.setPhone(user.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orderMapper.inser(orders);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        ShoppingCart shoppingCart = ShoppingCart.builder().userId(userId).build();
        for (ShoppingCart cart : shoppingCartMapper.selete(shoppingCart)) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.batchInserts(orderDetailList);
        shoppingCartMapper.clean(userId);
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception{
        // 当前登录用户id
        User user = userMapper.getByUserId(BaseContext.getCurrentId());

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    @Override
    public PageResult pageQuery(Integer page, Integer pageSize, Integer status) {
        PageHelper.startPage(page,pageSize);
        Orders orders = Orders.builder().userId(BaseContext.getCurrentId()).status(status).build();
        Page<OrderVO> list = orderMapper.pageQuery(orders);
        return new PageResult(list.getTotal(),list.getResult());
    }

    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.orderById(id);
        if(order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号:"+order.getNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    @Override
    public OrderVO details(Long id) {
        OrderVO vo = orderMapper.pageQuery(Orders.builder().id(id).build()).get(0);
        return vo;
    }

    @Override
    public void userCancelById(Long id) {
        OrderVO vo = orderPresence(id,null);
        Integer status = vo.getStatus();
        if(status != Orders.PENDING_PAYMENT && status != Orders.CANCELLED)
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        vo.setStatus(Orders.CANCELLED);
        orderMapper.updateStatus(vo);
    }

    @Override
    public void repetition(Long id) {
        OrderVO vo = orderPresence(id,null);
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = new ArrayList<>();
        vo.getOrderDetailList().forEach(e->{
            ShoppingCart s =new ShoppingCart();
            BeanUtils.copyProperties(e,s);
            s.setUserId(userId);
            shoppingCarts.add(s);
        });
        shoppingCartMapper.insertShoppingCarts(shoppingCarts);
    }
    //商家查看订单
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        Integer page = ordersPageQueryDTO.getPage();
        Integer pageSize = ordersPageQueryDTO.getPageSize();
        PageHelper.startPage(page,pageSize);
        Page<OrderVO> list = orderMapper.conditionSearch(ordersPageQueryDTO);
        return new PageResult(list.getTotal(),list.getResult());
    }
    //商家查询不同状态的订单数量
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        Page<OrderVO> list ;
        ordersPageQueryDTO.setStatus(Orders.TO_BE_CONFIRMED);
        list = orderMapper.conditionSearch(ordersPageQueryDTO);
        Integer toBeConfirmed = list != null ?list.size() :0;
        ordersPageQueryDTO.setStatus(Orders.CONFIRMED);
        list = orderMapper.conditionSearch(ordersPageQueryDTO);
        Integer confirmed = list != null ?list.size() :0;
        ordersPageQueryDTO.setStatus(Orders.DELIVERY_IN_PROGRESS);
        list = orderMapper.conditionSearch(ordersPageQueryDTO);
        Integer deliveryInProgress = list != null ?list.size() :0;
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }
    //商家接单
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        orderPresence(ordersConfirmDTO.getId(), Orders.TO_BE_CONFIRMED);
        OrderVO o = new OrderVO();
        BeanUtils.copyProperties(ordersConfirmDTO,o);
        orderMapper.updateStatus(o);
    }
    //商家拒单
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        OrderVO vo = orderPresence(ordersRejectionDTO.getId(), Orders.TO_BE_CONFIRMED);
        if(vo.getPayStatus() == Orders.PAID){
            refund(vo.getNumber());
        }
        Orders orders = new Orders();
        orders.setId(vo.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders, Collections.singletonList(orders.getId()));
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        OrderVO vo = orderPresence(ordersCancelDTO.getId(), Orders.TO_BE_CONFIRMED);
        if(vo.getPayStatus() == Orders.PAID){
            refund(vo.getNumber());
        }
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders, Collections.singletonList(orders.getId()));
    }

    @Override
    public void complete(Long id) throws Exception {
        OrderVO vo = orderPresence(id, Orders.DELIVERY_IN_PROGRESS);
        Orders orders = new Orders();
        orders.setId(vo.getId());
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders, Collections.singletonList(orders.getId()));
    }

    private OrderVO orderPresence(Long id, Integer status){
        if(id != null) throw new RuntimeException(MessageConstant.ORDER_ID_NOT_FOUND);
        OrderVO vo = orderMapper.pageQuery(Orders.builder().id(id).build()).get(0);
        if(vo == null) throw new RuntimeException(MessageConstant.ORDER_NOT_FOUND);
        if(status != null && vo.getStatus() != status)throw new RuntimeException(MessageConstant.ORDER_STATUS_ERROR);
        return vo;
    }
    private void refund(String number) throws Exception {
        String refund = weChatPayUtil.refund(
                number,
                number,
                new BigDecimal(0.01),
                new BigDecimal(0.01));
        log.info("申请退款：{}", refund);
    }
}
